<?php
namespace libraries;

use enums\ServiceEnums;
use enums\QueueEnums;
use enums\SmsEnums;
/**
 * @author fzq
 * @date 2016-09-08
 * @comment 知信发送类( 由于服务器将采用swoole故此处不再做过多的动态加载处理 )
 * 涉及到的文件及目录如下：config里的sms.php, libraries/sms/中的Trait, libraries中的Sms.php
 * services.php中配置如下:
 * 
 * $di->setShared( 'sms', function() use( $di ){
 *	$sms = Sms::getInstance( $di );
 *
 *	return $sms;
 * });
 * 
 * 使用方法:
 * $sms = $di->get( 'sms' );
 * $sms->getParam( SmsEnmus::BIZ_REGISTER );
 * $param[ 'mobile' ] = '15502921927';
 * $param['params'] = array( 'name' => 'bruce', 'code' => 'h2x8', 'hour' => 1 ); 
 * 
 * var_dump( $sms->sendSms( $sms ));
 */
class Sms implements \Phalcon\Di\InjectionAwareInterface
{
	private $_di;
	private $_smsCfg;
	private $_defaultSmsCfg;
// 	private $_redis;
	
	/**
	 * 服务提供商
	 */
	private $_arrServProvider;
	private static $_instance = null;
	
	public static function getInstance( $di )
	{
		if( !self::$_instance )
		{
			self::$_instance = new Sms( $di );
		}
			
		return self::$_instance;
	}
	
	private function __construct( $di )
	{
		if( $di != null )
		{
			$this->_di = $di;
			
			$this->_redis = $this->_di->get( ServiceEnums::SERVICE_NATIVE_REDIS );
			 
			$this->_smsCfg = $this->_di['smsCfg'];
			
			$this->_defaultSmsCfg = $this->_smsCfg->{ $this->_smsCfg->default };
		}

	}
	
	/**
	 * get param
	 * @param string $bizType
	 */
	public function getParam( $bizType = SmsEnums::BIZ_REGISTER )
	{
		$arrParams['params'] = $this->_smsCfg->{$this->_smsCfg->default}->{ 'tpl_' . $bizType }->params->toArray();
		$arrParams['tpl_id'] = $this->_smsCfg->{$this->_smsCfg->default}->{ 'tpl_' . $bizType }->id;
		$arrParams[ 'mobile' ] = '这里写上手机号码';
			
		return $arrParams;
	}
	 
	/**
	 * 发送SMS信息
	 * @param $sms 待发送的消息及相关配置
	 * 
	 * return false for error string ( message id for success )
	 */
	public function sendSms( $sms )
	{
		if( !is_array( $sms ) )
		{
			return false;
		}
		
		assert( $this->_di[ ServiceEnums::SERVICE_RQUEUE ] );
		
		$arrParam = $this->_di[ ServiceEnums::SERVICE_RQUEUE ]->getMsgProto( $sms, QueueEnums::QUEUE_SMS, QueueEnums::MSGTYPE_ARRAY );
		
		return $this->_di[ ServiceEnums::SERVICE_RQUEUE ]->push( $arrParam );
	}
	
// 	/**
// 	 * 
// 	 */
// 	private function isLimited( $arrParams )
// 	{
// 		if( $this->_redis->get( '' ) )
// 		{
			
// 		}
// 	}
	
	/* (non-PHPdoc)
	 * @see \Phalcon\Di\InjectionAwareInterface::setDI()
	 */
	public function setDI(\Phalcon\DiInterface $dependencyInjector) 
	{
		// TODO Auto-generated method stub
		$this->_di = $dependencyInjector;
		
		$this->_redis = $this->_di->get( ServiceEnums::SERVICE_NATIVE_REDIS );
		
	}

	/* (non-PHPdoc)
	 * @see \Phalcon\Di\InjectionAwareInterface::getDI()
	 */
	public function getDI() 
	{
		// TODO Auto-generated method stub
		return $this->_di;
	}
}